/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.KwStudent;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.mapper.StudentMapper;
import me.zhengjie.pojo.entity.Student;
import me.zhengjie.repository.KwStudentRepository;
import me.zhengjie.service.KwStudentService;
import me.zhengjie.service.dto.KwStudentDto;
import me.zhengjie.service.dto.KwStudentQueryCriteria;
import me.zhengjie.service.mapstruct.KwStudentMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author LongYang
* @date 2021-06-28
**/
@Service
@RequiredArgsConstructor
public class KwStudentServiceImpl implements KwStudentService {

    private final KwStudentRepository kwStudentRepository;
    private final KwStudentMapper kwStudentMapper;

    private final StudentMapper studentMapper;

    @Override
    public Map<String,Object> queryAll(KwStudentQueryCriteria criteria, Pageable pageable){
        Page<KwStudent> page = kwStudentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(kwStudentMapper::toDto));
    }

    @Override
    public List<KwStudentDto> queryAll(KwStudentQueryCriteria criteria){
        return kwStudentMapper.toDto(kwStudentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public KwStudentDto findById(Integer id) {
        KwStudent kwStudent = kwStudentRepository.findById(id).orElseGet(KwStudent::new);
        ValidationUtil.isNull(kwStudent.getId(),"KwStudent","id",id);
        return kwStudentMapper.toDto(kwStudent);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public KwStudentDto create(KwStudent resources) {
        if(StringUtils.isNotBlank(resources.getStudentNumber())){
            QueryWrapper<Student> jobNumberWrapper = new QueryWrapper<>();
            jobNumberWrapper.eq("student_number", resources.getStudentNumber());
            Integer jobNumberCount = studentMapper.selectCount(jobNumberWrapper);
            if (jobNumberCount != 0) throw new ParameterException("学号已存在");
        }
        QueryWrapper<Student> idCardWrapper = new QueryWrapper<>();
        idCardWrapper.eq("id_card", resources.getIdCard());
        Integer idCardCount = studentMapper.selectCount(idCardWrapper);
        if (idCardCount != 0) throw new ParameterException("身份证已存在");
        QueryWrapper<Student> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", resources.getPhone());
        Integer phoneCount = studentMapper.selectCount(phoneWrapper);
        if (phoneCount != 0) throw new ParameterException("手机号已存在");
        return kwStudentMapper.toDto(kwStudentRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(KwStudent resources) {
        if(StringUtils.isNotBlank(resources.getStudentNumber())){
            QueryWrapper<Student> jobNumberWrapper = new QueryWrapper<>();
            jobNumberWrapper.eq("student_number", resources.getStudentNumber())
                    .ne("id",resources.getId());
            Integer jobNumberCount = studentMapper.selectCount(jobNumberWrapper);
            if (jobNumberCount != 0) throw new ParameterException("学号已存在");
        }
        QueryWrapper<Student> idCardWrapper = new QueryWrapper<>();
        idCardWrapper.eq("id_card", resources.getIdCard())
                .ne("id",resources.getId());
        Integer idCardCount = studentMapper.selectCount(idCardWrapper);
        if (idCardCount != 0) throw new ParameterException("身份证已存在");
        QueryWrapper<Student> phoneWrapper = new QueryWrapper<>();
        phoneWrapper.eq("phone", resources.getPhone())
                .ne("id",resources.getId());
        Integer phoneCount = studentMapper.selectCount(phoneWrapper);
        if (phoneCount != 0) throw new ParameterException("手机号已存在");
        KwStudent kwStudent = kwStudentRepository.findById(resources.getId()).orElseGet(KwStudent::new);
        ValidationUtil.isNull( kwStudent.getId(),"KwStudent","id",resources.getId());
        kwStudent.copy(resources);
        kwStudentRepository.save(kwStudent);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            kwStudentRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<KwStudentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (KwStudentDto kwStudent : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("学号", kwStudent.getStudentNumber());
            map.put("姓名", kwStudent.getNameCn());
            map.put("身份证号", kwStudent.getIdCard());
            map.put("手机号", kwStudent.getPhone());
            map.put("学院", kwStudent.getCollege());
            map.put("删除标志（0.未删除，1.已删除）", kwStudent.getDelFlag());
            map.put("班级", kwStudent.getClasses());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}